import axios from 'axios'
const baseUrl = import.meta.env.VITE_AXIOS_BASE_URL;
interface UploadResponse {
  url: string
  [key: string]: any
}

interface UploadOptions {
  maxSize?: number // 最大文件大小，单位MB
  maxCount?: number // 最大上传数量
  accept?: string // 接受的文件类型
}

/**
 * 将文件转换为Base64
 * @param file 文件对象
 * @returns Promise<string> Base64字符串
 */
export const fileToBase64 = (file: File): Promise<string> => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result as string)
    reader.onerror = error => reject(error)
  })
}

/**
 * 验证文件
 * @param file 文件对象
 * @param options 验证选项
 * @returns string | null 错误信息或null
 */
export const validateFile = (file: File, options: UploadOptions = {}): string | null => {
  const { maxSize = 5, accept = 'image/*' } = options

  // 检查文件类型
  if (!file.type.match(accept.replace('*', '.*'))) {
    return '文件类型不支持'
  }

  // 检查文件大小
  if (file.size > maxSize * 1024 * 1024) {
    return `文件大小不能超过 ${maxSize}MB`
  }

  return null
}

/**
 * 上传单个文件
 * @param file 文件对象
 * @param onProgress 进度回调
 * @returns Promise<UploadResponse> 上传响应
 */
export const uploadFile = async (
  file: File,
  onProgress?: (progress: number) => void
): Promise<UploadResponse> => {
  const formData = new FormData()
  formData.append('file', file)
  
  try {
    const response = await axios.post<UploadResponse>(`${baseUrl}api/base64/upload`, formData, { 
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      onUploadProgress: (progressEvent) => {
        if (progressEvent.total && onProgress) {
          const progress = Math.round(
            (progressEvent.loaded * 100) / progressEvent.total
          )
          onProgress(progress)
        }
      }
    })

    return response.data
  } catch (error) {
    throw new Error('上传失败')
  }
}

/**
 * 上传多个文件
 * @param files 文件数组
 * @param options 上传选项
 * @param onProgress 进度回调
 * @returns Promise<UploadResponse[]> 上传响应数组
 */
export const uploadFiles = async (
  files: File[],
  options: UploadOptions = {},
  onProgress?: (index: number, progress: number) => void
): Promise<UploadResponse[]> => {
  const { maxCount = 5 } = options

  // 检查文件数量
  if (files.length > maxCount) {
    throw new Error(`最多只能上传 ${maxCount} 个文件`)
  }

  // 验证所有文件
  for (const file of files) {
    const error = validateFile(file, options)
    if (error) {
      throw new Error(error)
    }
  }

  // 上传所有文件
  const uploadPromises = files.map((file, index) => {
    console.log('Uploading file:', file)
    return uploadFile(file, (progress) => onProgress?.(index, progress))
  })

  return Promise.all(uploadPromises)
}

/**
 * 上传图片并转换为Base64
 * @param file 图片文件
 * @param onProgress 进度回调
 * @returns Promise<{ base64: string; response: UploadResponse }> Base64和上传响应
 */
export const uploadImageWithBase64 = async (
  file: File,
  onProgress?: (progress: number) => void
): Promise<{ base64: string; response: UploadResponse }> => {
  // 验证文件
  const error = validateFile(file, { accept: 'image/*' })
  if (error) {
    throw new Error(error)
  }

  // 转换为Base64
  const base64 = await fileToBase64(file)

  try {
    // 只上传 base64 数据
    const response = await axios.post<UploadResponse>(`${baseUrl}api/base64/upload`, {
      base64: base64
    }, {
      headers: {
        'Content-Type': 'application/json'
      },
      onUploadProgress: (progressEvent) => {
        if (progressEvent.total && onProgress) {
          const progress = Math.round(
            (progressEvent.loaded * 100) / progressEvent.total
          )
          onProgress(progress)
        }
      }
    })

    return { 
      base64, 
      response: response.data
    }
  } catch (error) {
    throw new Error('上传失败')
  }
}

/**
 * 上传多个图片并转换为Base64
 * @param files 图片文件数组
 * @param options 上传选项
 * @param onProgress 进度回调
 * @returns Promise<Array<{ base64: string; response: UploadResponse }>> Base64和上传响应数组
 */
export const uploadImagesWithBase64 = async (
  files: File[],
  options: UploadOptions = {},
  onProgress?: (index: number, progress: number) => void
): Promise<Array<{ base64: string; response: UploadResponse }>> => {
  const { maxCount = 5 } = options

  // 检查文件数量
  if (files.length > maxCount) {
    throw new Error(`最多只能上传 ${maxCount} 个文件`)
  }

  // 验证所有文件
  for (const file of files) {
    const error = validateFile(file, { ...options, accept: 'image/*' })
    if (error) {
      throw new Error(error)
    }
  }

  // 上传所有文件
  const uploadPromises = files.map((file, index) =>
    uploadImageWithBase64(file, (progress) => onProgress?.(index, progress))
  )

  return Promise.all(uploadPromises)
} 